package 周赛;

public class 句子中的有效单词 {

    public int countValidWords(String sentence) {
        int num = 0;
        String trim = sentence.trim();
        if (trim.equals(""))
            return 0;
        String[] s = trim.split(" ");
        for (String s1 : s) {
            if (s1.equals(""))
                continue;
            if (isWord(s1))
                num++;
        }
        return num;
    }
    public boolean isWord(String s){
        char[] punctuation = {'!','.',','};
        char[] chars = s.toCharArray();
        int length = chars.length;
        int num=0;
        if (chars[0]=='-' || chars[length-1]=='-')
            return false;
        for (int i = 0; i < length; i++) {
            if (Character.isDigit(chars[i]))
                return false;
            if (chars[i]=='-'){
                num++;
                if (num==2)
                    return false;
            }
            for (int j = 0; j < punctuation.length; j++) {
                if (chars[i]=='-' && chars[i+1]==punctuation[j])
                    return false;
                if (i!=length-1 && chars[i]==punctuation[j])
                    return false;
            }
        }
        return true;
    }
}
